package repository

import (
	mocker "gitee.com/fanbuchi/mocker/srv/proto/mocker"
	"github.com/jinzhu/gorm"
)

type Repository interface {
	CreateMocker(mocker *mocker.Mockers) error
	DeleteMocker(id int64)  error
	UpdateMocker(*mocker.Mockers) error
	FindOne(id int32) (*mocker.Mockers, error)
	SearchByField(*mocker.Mockers) (mockers []*mocker.Mockers, err error)
}



type Mocker struct {
	DB *gorm.DB
}




func (repo *Mocker) CreateMocker(mocker *mocker.Mockers) error {
	if err := repo.DB.Create(mocker).Error; err != nil {
		return err
	}
	return nil
}


func (repo *Mocker) DeleteMocker(id int64) error {
	if err := repo.DB.Delete(mocker.Mockers{Id:id}).Error; err != nil {
		return err
	}
	return nil
}

func (repo *Mocker) UpdateMocker(newMocker *mocker.Mockers) (*mocker.Mockers, error) {
	if err := repo.DB.Update(newMocker).Error; err != nil {
		return nil,err
	}
	result,err := repo.FindOne(newMocker.Id)
	if  err != nil {
		return nil,err
	}
	return result,nil
}


func (repo *Mocker) FindOne(id int64) (*mocker.Mockers, error) {
	var out=new(mocker.Mockers)
	if err := repo.DB.First(out,"ID = ?",id).Error; err != nil {
		if err==gorm.ErrRecordNotFound {
			return nil,nil
		}
		return nil,err
	}
	return out,nil
}


func (repo *Mocker) SearchByField(page *mocker.Page) (*[]*mocker.Mockers, error) {
	var out =new([]*mocker.Mockers)
	if err := repo.DB.Limit(page.Size).Offset((page.Page-1)*page.Size).Find(out,page.Param).Error; err != nil {
		return nil,err
	}
	return out,nil
}

/*func (model *mocker.Mockers) BeforeCreate(scope *gorm.Scope) error {
	uuid := uuid.New()
	return scope.SetColumn("ID", uuid.String())
}*/